import {Component, OnInit, ViewChild} from '@angular/core';
import {ColumnType, SPage, TablePageComponent} from "@shared/components/table-page/table-page.component";
import {MenuNodeItem} from "../../sys-setting/menu-manage/menu.service";
import {
  NzContextMenuService,
  NzDropdownMenuComponent,
  NzFormatEmitEvent,
  NzMessageService,
  NzModalService,
  NzTreeNode
} from "ng-zorro-antd";
import {AreaService} from "../../sys-setting/area-manage/area.service";
import {ApiService} from "@core/services/api";
import {HouseEditComponent} from "../house-edit/house-edit.component";
import {HttpClient} from "@angular/common/http";
import {RoomListComponent} from "../room-list/room-list.component";
import {PartmentEditComponent} from "../partment-edit/partment-edit.component";
import { ACLService } from '@delon/acl';
import { UtilService } from '@core/services/util.service';
declare var QRCode
import  html2canvas  from 'html2canvas'
import { AddBuildingBatchComponent } from '../add-building-batch/add-building-batch.component';

@Component({
  selector: 'app-house',
  templateUrl: './house.component.html',
  styleUrls: ['./house.component.less']
})
export class HouseComponent implements OnInit {
  @ViewChild('room', {static: false})room: RoomListComponent;
  node: MenuNodeItem[];
  searchValue: string = '';
  isSpinning:boolean=false;
  timeout:any="";
  config: SPage = {
    columns: [
      {
        index: 'id',
        title: '选中',
        type: ColumnType.checkbox
      },
      {
        index: 'houseName',
        title: '房屋名称',
        filter: {
          type: 'string'
        }
      },
      {
        index: 'houseAddress',
        title: '房屋地址',
        filter: {
          type: 'string'
        }
      },
      {
        index: 'houseFloors',
        title: '楼层'
      },
      {
        index: 'houseRooms',
        title: '房间数'
      },
      {
        index: 'areaName',
        title: '所属区域',
        filter: {
          type: 'string'
        }
      },
      {
        index: 'houseType',
        title: '类型',
        filter: {
          type: 'select',
          items: [
            {label: '出租屋', value:'1'},
            {label: '厂房', value:'2'},
            {label: '公寓', value: '3'},
            {label: '写字楼', value: '4'},
            {label: '商业住宅', value: '5'},
            {label: '其他', value: '6'},
          ]
        }
      },
      {
        index: 'status',
        title: '数据状态',
        type: ColumnType.tag,
        tag: {
          false: {text:'停用', color: 'red'},
          true: {text:'启用', color: 'green'},
        },
        filter: {
          type: 'select',
          items: [
            {label: '启用', value: true},
            {label: '停用', value: false},
          ]
        }
      },
      {
        index: 'houseRemark',
        title: '备注'
      },
    ],
    reqUrl: this.api.house.page.url,
    editBtn: [
      {title: '查看'},
      {title: '房间管理'}
    ]
  };
  selectedData: object[];
  communityList: object[];
  activedNode: NzTreeNode;

  editDic(type: 0 | 1 | 2 | 3 | 4 | 5 = 0, param?: object): void {
    let title = '';
    switch (type) {
      case 0:
        title = '新增楼栋';
        break;
      case 1:
        title = '编辑楼栋';
        break
      case 2:
        this.msg.warning('功能正在开发中!')
        return;
      case 3:
        title = '房屋详情';
        break;
      case 4:
        title = '新增单元';
        break;
      case 5:
        title = '编辑单元';
        break
    }
    if (this.activedNode && this.activedNode['key']) {
      console.log(this.activeItem.id)
      param['areaId'] = this.activedNode['key'];
      param['parentName'] = this.activedNode['title'];
    }
    if (type <= 3) {
      this.modal.create({
        nzTitle: title,
        nzContent: HouseEditComponent,
        nzWidth: 800,
        nzComponentParams: {
          type,
          _param : param
        },
        nzOnOk: () => {
          this.feachCommunity(this.searchValue);
        },
        nzFooter: null
      })
    }
    if (type > 3) {
      this.modal.create({
        nzTitle: title,
        nzContent: PartmentEditComponent,
        nzWidth: 800,
        nzComponentParams: {
          type,
          _param : param
        },
        nzOnOk: () => {
          this.feachCommunity(this.searchValue);
        },
        nzFooter: null
      })

    }
  }
  //删除楼栋或者单元
  deleteBuilding():void{
   console.log(this.activedNode) 
   const id = this.activedNode.origin.key
   const areaRank = this.activedNode.origin.rank
    this.modal.confirm({
      nzTitle: '确定删除？',
      nzOnOk: () => {
        const body = [];
        this.http.request<any>("post","/core/city/area/delete",{body:{"id":id,"areaRank":areaRank}}).subscribe(res => {
          if (res.status === '200') {
            this.msg.success('删除成功');
            // this.st.reload();
            this.feachCommunity(this.searchValue)
          }else{
            this.msg.error(res.message)
          }
        })

      }
    })
  }
  //批量新增楼栋
  addBuildingBatch(){
    const id = this.activedNode.key
    this.modal.create({
      nzTitle : "批量新增楼栋",
      nzContent : AddBuildingBatchComponent,
      nzWidth : 600,
      nzComponentParams:{
        id
      },
      nzOnOk: () => {
        this.feachCommunity(this.searchValue)
      },
      nzFooter: null
    })
  }
  selectChange(e): void {
    this.selectedData = e;
  }
  operate(e): void {
    console.log(e);
    switch (e.title) {
      case '查看':
        this.editDic(1, e.data);
        break;
      case '房间管理':
        this.roomManage(e.data)
    }
  }
  //删除
  deleteDic(): void {
    if (!this.selectedData || this.selectedData.length === 0) {
      this.msg.warning('请选择数据后操作');
      return;
    }
    this.modal.confirm({
      nzTitle: '您确定要删除这些数据吗',
      nzOnOk: () => {
        const body = [];
        this.selectedData.forEach((item: any) => {
          body.push({id: item.id})
        })
        this.http.put<any>(this.api.house.delete.url,body).subscribe(res => {
          if (res.status === '200') {
            this.msg.success('删除成功');
            // this.st.reload();
            this.feachCommunity(this.searchValue)
          }else{
            this.msg.error(res.message)
          }
        })

      }
    })
  }
  activeItem = null
  selectChage(event): void {
    this.activeNode(event)
    console.log(this.activedNode)
    // this.room.st.reload();
  }
  //鼠标右键树形列表
  contextMenu($event: MouseEvent, menu: NzDropdownMenuComponent, node: any): void {
    this.activedNode = node;
    this.activeItem = node;
    console.log(this.activedNode);
    this.nzContextMenuService.create($event, menu);
  }
  roomManage(param): void {
    this.modal.create({
      nzTitle:  '房间管理',
      nzContent: RoomListComponent,
      nzWidth: 1200,
      nzComponentParams: {
        _param : param
      },
      nzOnOk: () => {
        // this.st.reload();
      },
      nzFooter: null
    })
  }

  onKey(event){
    let fn=this.debounce(this.feachCommunity,1000,event.target.value)
    fn()
  }
  debounce(fn,wait,data){
    const self=this
    return ()=>{
      if(self.timeout) clearTimeout(self.timeout)
      self.timeout=setTimeout(()=>{
        fn.call(self,data)
      },wait)
    }
  }

  feachCommunity(name): void {
    this.http.post(this.api.area.treeList.url, {'name':name}).subscribe((res: any) => {
      if (res.status == '200') {
        let arr = res.data.map(item => {
          return {
            key: item.id,
            title: item.name,
            level: 0,
            id:item.id,
            pId:item.parentId,
            rank:item.rank,
            cityId:item.cityId
          }
        })
        if(this.util.getStorage("userAccount") == '"admin"'){
          this.communityList=arr
        }else{
          // console.log(this.transformTree(arr))
          // this.communityList=this.transformTree(arr);
          this.communityList = arr
        }
      }
    })
  }

   //扁平化数据转树形结构
   transformTree(obj){
      let copyedObj = JSON.parse(JSON.stringify(obj))  //深拷贝源数据
      return copyedObj.filter(parent=>{
              let findChildren = copyedObj.filter(child=>{
                return parent.id == child.pId && child.cityId == null
              })
              if(parent.rank == 6){//小区，下级是楼栋单元,对楼栋单元进行排序
                findChildren = this.buildingSort(findChildren)
              }
              if(parent.rank == 8){
                findChildren = this.buildingSort(findChildren)
              }
              findChildren.length>0 ? parent.children = findChildren : parent.children = []
                return parent.cityId != null  //返回顶层，依据实际情况判断这里的返回值
              })
    }

  //楼栋单元排序
  buildingSort(arr){
    arr.sort((a,b)=>{
      if(a.rank == 8){//楼栋
        let v=a.title.substring(0,a.title.length-1)
        let k=b.title.substring(0,b.title.length-1)
        return v-k
      }else if(a.rank == 9){//单元

        let i=a.title.substring(0,a.title.length-2)
        let j=b.title.substring(0,b.title.length-2)
        return i-j
      }
    })
    return arr
  }

  //点击展开树形菜单
  nzEvent(event: NzFormatEmitEvent): void {
    // load child async
    if (event.eventName === 'expand') {
      const node = event.node;
      if (node && node.getChildren().length === 0 && node.isExpanded) {
        console.log(node)
        this.loadNode(event.node).then(data => {
          console.log(data)
          if(data.length > 0 && data[0].rank == 9) {
            data.forEach( item => {
              item.isLeaf = true;
            })
          }
          node.addChildren(data);
        }, () => {
          node.addChildren([])
        });
      }
    }
  }
  loadNode(data): Promise <any>{
    return this.area.getAreaTreeNode(data.key)
  }
  activeNode(data: NzFormatEmitEvent): void {
    this.activedNode = data.node!;
    this.activeItem = data.node;
  }
  selectDropdown(type: 0 | 1): void {
    console.log(this.activedNode)
    if (type == 0) {
      if (this.activedNode.origin.rank < 8) {
        this.editDic(0, {})
      } else {
        const param = {}
         param['parentAllId'] = this.activedNode.origin.parentAllId;
        this.editDic(4, param)
      }
    } else {
      if (this.activedNode.origin.rank == 8) {
        this.editDic(1, {id: this.activedNode.key})
      } else {
        this.editDic(5, {id: this.activedNode.key})
      }
    }
  }
  openFolder(data: NzTreeNode | Required<NzFormatEmitEvent>): void {
    // do something if u want
    if (data instanceof NzTreeNode) {
      data.isExpanded = !data.isExpanded;
    } else {
      const node = data.node;
      if (node) {
        node.isExpanded = !node.isExpanded;
      }
    }
  }
  //查看二维码
  watchQRCode(data):void{
    console.log(data)
    let url="https://applet.xtxspmj.com/miniprogram/call?address="+data.key
    const modal = this.modal.create({
      nzTitle: '楼栋单元二维码',
      nzContent: '<div class="imgDiv"><div class="qrcode" id="imgDiv"></div><div>广东省,深圳市,宝安区,新安街道,威马社区,威马小区,1栋,一单元</div></div>',
      nzWidth: 400,
      nzFooter: [
        {
          label:"下载二维码",
          type:"primary",
          onClick:()=>{
            const scale = window.devicePixelRatio
            const width = (document.querySelector(".imgDiv") as HTMLDivElement).offsetWidth 
            const height = (document.querySelector(".imgDiv") as HTMLDivElement).offsetHeight
            let dom:any=document.querySelector(".imgDiv")
            html2canvas(dom,{
              scale,
              width:width,
              height:height,
              useCORS:true
            }).then(canvas => {
              let dataURL = canvas.toDataURL("image/png")
              if (dataURL !== "") {
                let a = document.createElement('a')
                a.download = "二维码.jpg";
                a.href = dataURL;
                a.click()
              }
            })
          }
        }
      ],
    })
    modal.afterOpen.subscribe(()=>{
      new QRCode(document.getElementsByClassName("qrcode")[0],{
        width:350,
        height:350
      }).makeCode(url);
    })
  }

  constructor(
    private modal: NzModalService,
    private msg: NzMessageService,
    private area: AreaService,
    private api: ApiService,
    private http: HttpClient,
    private nzContextMenuService: NzContextMenuService,
    private aclService: ACLService,
    private util: UtilService,
  ) {
    this.feachCommunity("")
  }


  ngOnInit() {
    /*this.area.getAreaTreeNode({id: '440304'}).then(
      res => {
        this.node = [res];
      }
    )*/

  }

}
